package com.heking.securityapp.pages;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.widget.Button;

import com.heking.security.LogUtils;
import com.heking.security.encryption.AESHelper;
import com.heking.security.encryption.Base64Utils;
import com.heking.security.encryption.EncryptConstants;
import com.heking.security.encryption.RSAHelper;
import com.heking.securityapp.R;
import com.heking.securityapp.UriUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * @Author 35574
 * @Date 2021/10/26
 * @Description
 */
public class EncryptActivity extends AppCompatActivity {
    private static final String TAG = ">>>EncryptActivity";
    //512 64
//    private static final String PUBLIC_KEY="MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ/rQynW6pgjG3A+rurdeHeeqYmIhPy4ZbV8SD5YJzMwoDblEH9Ft2nJ+COdgwE1/0adGU5iGKJIw/auOtRum6ECAwEAAQ==";
//    private static final String PRIVATE_KEY="MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAn+tDKdbqmCMbcD6u6t14d56piYiE/LhltXxIPlgnMzCgNuUQf0W3acn4I52DATX/Rp0ZTmIYokjD9q461G6boQIDAQABAkA+gQaEQOL6SaZ8zZMyaxOdtV7QSZKo8C2YrJXUAEJ6B+YcFmUzoNQF39IBm3FGib3iXFq2V12vCaUQhUEuna1BAiEA0pHkWMSv6GqSHqC12vuRAGmcyAu9IlEoUCmsv94/HVkCIQDCa9db6ZPNoXb0MQIm6GvlET+MtWLpHt94KqXRJwc/iQIgCGoyIOYDTZtsqXKsscqZ2dVeoZPug/+QR9vSfnxoM0kCIQC4S9m9utDs394O5FYR48hDP/Jpw5ebPDTBiEve04w/YQIgYQs1IypaANGSuz/eQgwli+EC0M8fBDamASfvVQdNS0w=";

    //1024 128
    private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsz9ehtLYrWS7s6sN+WGVBGuvcIc7d3/FF66YPO7LSoMItc8VYRlqsPbeEEp1C3xBzWjdg/GmILpjSiFVtfcNE+tiwJ1ktABQo8LZteKsMwTnPfk/7afVJKkJd+6u9tIcaXCJQ+65O8RIE57AWlT2yJdPLqDfa9e6+WpkLAbWh8QIDAQAB";
    private static final String PRIVATE_KEY = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKzP16G0titZLuzqw35YZUEa69whzt3f8UXrpg87stKgwi1zxVhGWqw9t4QSnULfEHNaN2D8aYgumNKIVW19w0T62LAnWS0AFCjwtm14qwzBOc9+T/tp9UkqQl37q720hxpcIlD7rk7xEgTnsBaVPbIl08uoN9r17r5amQsBtaHxAgMBAAECgYAZogaxFLYEvgjI2ZW/0urJ+m1LzLP7kzEdlvOdxNQki/Xheg+mpWDjtY/YBk7PUXkGMzaNq0MYERlX+SL6x7HD9hxeHonunKV8ZIZB9zypxSP2tA1CSuKQSqF7Y4niBSN5XpY3wIPWPCv42yqub2aUXhao03aUtHij28sT16uWcQJBANzmTUE381DCiHdO9te2Ak9mOftuCKhZurcqK223ZwcsDrpMbkLUnralXi0y3ofDnWyv5pcBIQN7uYlytdPjB0UCQQDIRXCl7KGB6knObAGjBWT9F3PoYLA0YNNIkePJaUAHWtJGBGJErBwK28G+h9DltgZhJ7cwW2f98tAH4ACSdnS9AkAEUVgXO0G9RWAnfNqkUsFuzd+6Q2dV6xMUO3XH2jrgUAMlrxLEqaVEiqzxkzn4S2GLW1DViMcda1CwGBbnwltFAkBxUrm3afrJ5KT25S7X7EmE3Sx9JZkPSmrD+amHYsMUZlPtwrVIXotPqaIsCfYuxZ0+hJaoClEB5c/JZPtt5RGRAkAORb+XXdQDPfINDr9Kx4GrTMaI3q//s2lhlU3o2Tw6AsBhBOAv6Df0wjYSp/Cb3vDsAm8ylLkyGEMdBemjJtW6";
    //2048  256
//    private static final String PUBLIC_KEY="M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V37Vvv32DWSx9AYEXPxbPIVkrj0cqMtzP75LvJs/jZiK8h49EsOC2EydmSjIrpTMH5r9v0maP3ORG/FQUgdTL/Vm8VTIx1zDFJ+S6flWQ661bDvssobFja2tWXkYCyFQHxPUAXX9zid2mXVwucNYkzYwS6D1o5yCYsZ5y2HVh6vSxxjvC+tcl54FTqjAQbL+xE6Yi/kOBx7jR1eQjfJs88jtG5lM8NtAoIBAF7wjIy3wzGBcXDWr+GiLA6WxTuGhUAcyrhpxRwWPS/Zi6J9y6eYujmn3uR66BTN65lYNyAQY3y6wlABxexpOydHbneLvHSh2k5x9NQTGU7MYSS1RPfh1Wq/4xlSd0qiYSFBx97pKeOl0WmWYyv6Xs1UKibLGMBIFKzq2a67s86AaXMHLtcNbQeXl64Bq/uBlJgfv3xC+HfJSReddydNDCeVNil68R230camLhIZF6hbBHJxKx+G4h8xJbMQXzBt5apeOIS/FDa3VRxrT50g0j3nhE/QOepZZIVQIc2QBAXvNKxxkiWrZmifJ8Z/fskRQix0dh+oH8yLh1FQ0WFH3s4=";

    private static final int REQUEST_ENCRYPT_FILE = 1000;
    private static final int REQUEST_DECRYPT_FILE = 2000;

    private Button mBtn1;
    private Button mBtn2;
    private Button mBtn3;
    private Button mBtn4;
    private Button mBtn5;
    private Button mBtn6;
    private Button mBtn7;
    private Button mBtn31;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.encrypt_activity);
        findViews();
        addListener();

    }

    private void findViews() {
        mBtn1 = findViewById(R.id.btn1);
        mBtn2 = findViewById(R.id.btn2);
        mBtn3 = findViewById(R.id.btn3);
        mBtn4 = findViewById(R.id.btn4);
        mBtn5 = findViewById(R.id.btn5);
        mBtn6 = findViewById(R.id.btn6);
        mBtn7 = findViewById(R.id.btn7);
        mBtn31 = findViewById(R.id.btn3_1);
    }

    private String data = "sdfsdfsdfsdfshghkdfkdfngdkf5415315fj4475745sdjksdjf12sjdfk45612242s4465dfgdfgdfgdfgdf6541fsdfssdfsdfsd4641sdfsdfsdfsdfadfsdf215454!@^$*&5454水电费sd据了解爱丽舍大街上的是的发生sdfsadfshgthjfj的时间到了伤筋号上的舰载雷达系统、舰载sdgasdgsdg机阻拦索等关键等设备4534534依然没有安装列EL/M-2248 MF-STAR多功能相控阵雷达依然缺装，同时该舰依然没有安装阻拦索。这使得这艘航母的状态基本与印度到位动骨蓝色的号是印度维克兰特级航空sdgsdgsd465451母舰的首舰，该舰同时也3453453是印度首次sdgsdgsd自行建造的4534534航空母舰，由科钦造船厂负责建造";
    private int flags = Base64.NO_WRAP;
    private Charset charset = StandardCharsets.UTF_8;

    private void addListener() {
        mBtn31.setOnClickListener(v -> {
//            RSAHelper.calculateEncryptBlockLength(PUBLIC_KEY);
//            RSAHelper.calculateDecryptBlockLength(PUBLIC_KEY);
//            LogUtils.d(TAG, "######################");
//            RSAHelper.calculateEncryptBlockLength(PUBLIC_KEY1);
//            RSAHelper.calculateDecryptBlockLength(PUBLIC_KEY1);
            RSAHelper iEncryptor = new RSAHelper.Builder()
                    .setBase64Flag(flags)
                    .setCharset(charset)
                    .setTransformation("RSA/None/PKCS1Padding")
                    .setPublicKey(PUBLIC_KEY)
                    .setPrivateKey(PRIVATE_KEY)
                    .build();
            iEncryptor.getOutputLength();


        });
        //base64
        mBtn1.setOnClickListener(v -> {

            final Base64Utils base64Utils = new Base64Utils(charset, flags);
            for (int j = 1; j <= data.length(); j++) {
                String source = data.substring(0, j);
                LogUtils.d(TAG, "明文:" + source + ",长度:" + source.length());
                byte[] bytes = source.getBytes();//StandardCharsets.UTF_8
                byte[] encode = base64Utils.encode(bytes);
                String encodeS = new String(encode, 0, encode.length, StandardCharsets.US_ASCII);
                LogUtils.d(TAG, "秘文:" + encodeS + ",长度:" + encodeS.length());

                LogUtils.d(TAG, "明文byte长度:" + bytes.length + ",秘文byte长度:" + encode.length);

                int calculate = base64Utils.calculateSecretLength(bytes.length);
                boolean b = calculate == encode.length;
                if (b) {
                    LogUtils.d(TAG, "calculate:" + calculate + "," + b);
                } else {
                    LogUtils.e(TAG, "calculate:" + calculate + "," + b);
                }
                LogUtils.d(TAG, "###########################");
            }


        });
        //AES
        mBtn2.setOnClickListener(v -> {
            AESHelper iEncryptor = new AESHelper.Builder()
                    .setBase64Flag(flags)
                    .setCharset(charset)
//                    .setTransformation(EncryptConstants.TRANSFORMATION_AES_CBC_P7)
                    .setTransformation("AES/CBC/PKCS5Padding")
                    .setIv("0123456789123456")
//                    .setKey("9e6aae62a2e24edf")//16:128
                    .setKey("9e6aae62a2e24edf99a2cbce")//24:192
//                    .setKey("9e6aae62a2e24edf99a2cbcebf1261a7")//32:256
                    .build();
            for (int j = 1; j <= data.length(); j++) {
                String source = data.substring(0, j);
                LogUtils.d(TAG, "明文:" + source + ",长度:" + source.length());
                byte[] bytes = source.getBytes();
                byte[] encrypt = iEncryptor.encrypt(bytes);
                LogUtils.w(TAG, "明文byte长度:" + bytes.length + ",秘文byte长度:" + encrypt.length);
                Base64Utils base64Utils = iEncryptor.getBase64Utils();
                String base64S = base64Utils.encodeToString(encrypt);
                LogUtils.d(TAG, "秘文base64:" + base64S + ",长度" + base64S.length());//(明文长度/16+1)*16
                int calculate = AESHelper.calculateSecretLength(bytes.length, true);
                if (calculate == encrypt.length) {
                    LogUtils.d(TAG, "calculate=" + calculate + ",true");
                } else {
                    LogUtils.e(TAG, "calculate=" + calculate + ",false");
                }

                LogUtils.d(TAG, "###########################");

            }
        });

        //RAS
        mBtn3.setOnClickListener(v -> {
            RSAHelper iEncryptor = new RSAHelper.Builder()
                    .setBase64Flag(flags)
                    .setCharset(charset)
                    .setTransformation("RSA/None/PKCS1Padding")
                    .setPublicKey(PUBLIC_KEY)
                    .setPrivateKey(PRIVATE_KEY)
                    .build();
            byte[] bytes1 = PUBLIC_KEY.getBytes();
            Base64Utils base64Utils1 = new Base64Utils(charset, Base64.NO_WRAP);
            byte[] decode = base64Utils1.decode(bytes1);
            LogUtils.d(TAG, "PUBLIC_KEY length:" + decode.length);

            for (int j = 1; j <= data.length(); j++) {
                String source = data.substring(0, j);
                LogUtils.d(TAG, "明文:" + source + ",长度:" + source.length());
                byte[] bytes = source.getBytes();
                byte[] encrypt = iEncryptor.encrypt(bytes, 0, bytes.length);
                LogUtils.w(TAG, "明文byte长度:" + bytes.length + ",秘文byte长度:" + encrypt.length);
                Base64Utils base64Utils = iEncryptor.getBase64Utils();
                String base64S = base64Utils.encodeToString(encrypt);
                LogUtils.d(TAG, "秘文base64:" + base64S + ",长度" + base64S.length());//(明文长度/16+1)*16

                String decrypt = iEncryptor.decryptToString(encrypt);
                LogUtils.d(TAG, "decrypt:" + decrypt);

                LogUtils.d(TAG, "###########################");

            }
        });
        //AES加密文件
        mBtn4.setOnClickListener(v -> {
//            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.setType("*/*");
//            startActivityForResult(intent,REQUEST_ENCRYPT_FILE);
            File dest = new File(Environment.getExternalStorageDirectory(), "1/src/");
            if (dest.exists() && dest.isDirectory()) {
                File[] files = dest.listFiles();
                for (File item : files) {
                    encryptFileAes1(item.getAbsolutePath());
                }
            }
          /*  File file=new File(dest,"123.txt");
            encryptFileAes1(file.getAbsolutePath());*/

        });
        //AES解密文件
        mBtn5.setOnClickListener(v -> {
//            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.setType("*/*");
//            startActivityForResult(intent,REQUEST_DECRYPT_FILE);
            File dest = new File(Environment.getExternalStorageDirectory(), "1/aes_encrypt/");
            if (dest.exists() && dest.isDirectory()) {
                File[] files = dest.listFiles();
                for (File item : files) {
                    decryptFileAes1(item.getAbsolutePath());
                }
            }

        });

        //RSA加密文件
        mBtn6.setOnClickListener(v -> {
//            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.setType("*/*");
//            startActivityForResult(intent,REQUEST_ENCRYPT_FILE);
            File dest = new File(Environment.getExternalStorageDirectory(), "1/src/");
            if (dest.exists() && dest.isDirectory()) {
                File[] files = dest.listFiles();
                for (File item : files) {
                    encryptFileRsa1(item.getAbsolutePath());
                }
            }
          /*  File file=new File(dest,"123.txt");
            encryptFileRsa1(file.getAbsolutePath());*/



        });
        //RSA解密文件
        mBtn7.setOnClickListener(v -> {
//            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.setType("*/*");
//            startActivityForResult(intent,REQUEST_DECRYPT_FILE);
            File dest = new File(Environment.getExternalStorageDirectory(), "1/rsa_encrypt/");
            if (dest.exists() && dest.isDirectory()) {
                File[] files = dest.listFiles();
                for (File item : files) {
                    decryptFileRsa1(item.getAbsolutePath());
                }
            }

        });

    }

    private static final int BLOCK_LENGTH = 1024;//分段长度
    private static final String SUFFIX = ".encrypt";

    private void encryptFileAes(final String path) {
        LogUtils.d(TAG, "path=" + path);
        if (path == null) {
            LogUtils.e(TAG, "文件路径不能为空");
            return;
        } else if (path.endsWith(SUFFIX)) {
            LogUtils.e(TAG, "文件无需加密");
            return;
        }

        AESHelper iEncryptor = new AESHelper.Builder()
                .setBase64Flag(flags)
                .setCharset(charset)
//                    .setTransformation(EncryptConstants.TRANSFORMATION_AES_CBC_P7)
                .setTransformation("AES/CBC/PKCS5Padding")
                .setIv("0123456789123456")
//                    .setKey("9e6aae62a2e24edf")//16:128
                .setKey("9e6aae62a2e24edf99a2cbce")//24:192
//                    .setKey("9e6aae62a2e24edf99a2cbcebf1261a7")//32:256
                .build();
        new Thread(() -> {
            File source = new File(path);
            File dest = new File(Environment.getExternalStorageDirectory(), "1/aes_encrypt/" + source.getName() + SUFFIX);
            LogUtils.d(TAG, "dest=" + dest.getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(source);
                fos = new FileOutputStream(dest);
                int len = 0;
                byte[] buf = new byte[BLOCK_LENGTH];
                while ((len = fis.read(buf)) > 0) {
                    LogUtils.d(TAG, "len=" + len);
                    byte[] encrypt = iEncryptor.encrypt(buf, 0, len);
                    fos.write(encrypt, 0, encrypt.length);
                }
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }).start();
    }

    private void decryptFileAes(final String path) {
        LogUtils.d(TAG, "path=" + path);
        if (path == null) {
            LogUtils.e(TAG, "文件路径不能为空");
            return;
        } else if (!path.endsWith(SUFFIX)) {
            LogUtils.e(TAG, "文件无需解密");
            return;
        }
        AESHelper iEncryptor = new AESHelper.Builder()
                .setBase64Flag(flags)
                .setCharset(charset)
//                    .setTransformation(EncryptConstants.TRANSFORMATION_AES_CBC_P7)
                .setTransformation("AES/CBC/PKCS5Padding")
                .setIv("0123456789123456")
//                    .setKey("9e6aae62a2e24edf")//16:128
                .setKey("9e6aae62a2e24edf99a2cbce")//24:192
//                    .setKey("9e6aae62a2e24edf99a2cbcebf1261a7")//32:256
                .build();
        new Thread(() -> {
            File source = new File(path);
            int index = path.lastIndexOf("/");
            File dest = new File(Environment.getExternalStorageDirectory(), "1/aes_decrypt/" + path.substring(index + 1).replace(SUFFIX, ""));
            LogUtils.d(TAG, "dest=" + dest.getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(source);
                fos = new FileOutputStream(dest);
                int len = 0;
                int outputSize = AESHelper.calculateSecretLength(BLOCK_LENGTH, true);
                LogUtils.d(TAG, "outputSize=" + outputSize);
                byte[] buf = new byte[outputSize];
                while ((len = fis.read(buf)) > 0) {
                    byte[] encrypt = iEncryptor.decrypt(buf, 0, len);
                    fos.write(encrypt, 0, encrypt.length);
                }
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }).start();
    }

    private void encryptFileAes1(final String path) {
        LogUtils.d(TAG, "path=" + path);
        if (path == null) {
            LogUtils.e(TAG, "文件路径不能为空");
            return;
        } else if (path.endsWith(SUFFIX)) {
            LogUtils.e(TAG, "文件无需加密");
            return;
        }

        AESHelper iEncryptor = new AESHelper.Builder()
                .setBase64Flag(flags)
                .setCharset(charset)
                    .setTransformation(EncryptConstants.TRANSFORMATION_AES_CBC_P7)
//                .setTransformation("AES/CBC/PKCS5Padding")
                .setIv("0123456789123456")
//                    .setKey("9e6aae62a2e24edf")//16:128
                .setKey("9e6aae62a2e24edf99a2cbce")//24:192
//                    .setKey("9e6aae62a2e24edf99a2cbcebf1261a7")//32:256
                .build();
        new Thread(() -> {
            File source = new File(path);
            File dest = new File(Environment.getExternalStorageDirectory(), "1/aes_encrypt/" + source.getName() + SUFFIX);
            LogUtils.d(TAG, "dest=" + dest.getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(source);
                fos = new FileOutputStream(dest);
               iEncryptor.encrypt(fis,fos);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }).start();
    }

    private void decryptFileAes1(final String path) {
        LogUtils.d(TAG, "path=" + path);
        if (path == null) {
            LogUtils.e(TAG, "文件路径不能为空");
            return;
        } else if (!path.endsWith(SUFFIX)) {
            LogUtils.e(TAG, "文件无需解密");
            return;
        }
        AESHelper iEncryptor = new AESHelper.Builder()
                .setBase64Flag(flags)
                .setCharset(charset)
                    .setTransformation(EncryptConstants.TRANSFORMATION_AES_CBC_P7)
//                .setTransformation("AES/CBC/PKCS5Padding")
                .setIv("0123456789123456")
//                    .setKey("9e6aae62a2e24edf")//16:128
                .setKey("9e6aae62a2e24edf99a2cbce")//24:192
//                    .setKey("9e6aae62a2e24edf99a2cbcebf1261a7")//32:256
                .build();
        new Thread(() -> {
            File source = new File(path);
            int index = path.lastIndexOf("/");
            File dest = new File(Environment.getExternalStorageDirectory(), "1/aes_decrypt/" + path.substring(index + 1).replace(SUFFIX, ""));
            LogUtils.d(TAG, "dest=" + dest.getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(source);
                fos = new FileOutputStream(dest);
                iEncryptor.decrypt(fis,fos);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }).start();
    }

    private void encryptFileRsa(final String path) {
        LogUtils.d(TAG, "path=" + path);
        if (path == null) {
            LogUtils.e(TAG, "文件路径不能为空");
            return;
        } else if (path.endsWith(SUFFIX)) {
            LogUtils.e(TAG, "文件无需加密");
            return;
        }

        RSAHelper iEncryptor = new RSAHelper.Builder()
                .setBase64Flag(flags)
                .setCharset(charset)
                .setTransformation("RSA/None/PKCS1Padding")
                .setPublicKey(PUBLIC_KEY)
                .setPrivateKey(PRIVATE_KEY)
                .build();
        new Thread(() -> {
            File source = new File(path);
            File dest = new File(Environment.getExternalStorageDirectory(), "1/rsa_encrypt/" + source.getName() + SUFFIX);
            LogUtils.d(TAG, "dest=" + dest.getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(source);
                fos = new FileOutputStream(dest);
                int len = 0;
                byte[] buf = new byte[BLOCK_LENGTH];
                while ((len = fis.read(buf)) > 0) {
                    LogUtils.d(TAG, "len=" + len);
                    byte[] encrypt = iEncryptor.encrypt(buf, 0, len);
                    LogUtils.d(TAG, "encrypt.length=" + encrypt.length);
                    fos.write(encrypt, 0, encrypt.length);
                }
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }).start();
    }

    private void decryptFileRsa(final String path) {
        LogUtils.d(TAG, "path=" + path);
        if (path == null) {
            LogUtils.e(TAG, "文件路径不能为空");
            return;
        } else if (!path.endsWith(SUFFIX)) {
            LogUtils.e(TAG, "文件无需解密");
            return;
        }
        RSAHelper iEncryptor = new RSAHelper.Builder()
                .setBase64Flag(flags)
                .setCharset(charset)
                .setTransformation("RSA/None/PKCS1Padding")
                .setPublicKey(PUBLIC_KEY)
                .setPrivateKey(PRIVATE_KEY)
                .build();
        new Thread(() -> {
            File source = new File(path);
            int index = path.lastIndexOf("/");
            File dest = new File(Environment.getExternalStorageDirectory(), "1/rsa_decrypt/" + path.substring(index + 1).replace(SUFFIX, ""));
            LogUtils.d(TAG, "dest=" + dest.getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(source);
                fos = new FileOutputStream(dest);
                int outputLen = iEncryptor.calculateSecretLength(BLOCK_LENGTH);
                LogUtils.d(TAG, "outputLen=" + outputLen);
                byte[] buf = new byte[outputLen];
                int len = 0;
                while ((len = fis.read(buf)) > 0) {
                    LogUtils.d(TAG, "len=" + len);
                    byte[] decrypt = iEncryptor.decrypt(buf, 0, len);
                    LogUtils.d(TAG,"decrypt.length="+decrypt.length);
//                    Logger.d(TAG,"decrypt="+new String(decrypt,0,decrypt.length,StandardCharsets.UTF_8));

                    fos.write(decrypt, 0, decrypt.length);
                }
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }).start();
    }

    private void encryptFileRsa1(final String path) {
        LogUtils.d(TAG, "path=" + path);
        if (path == null) {
            LogUtils.e(TAG, "文件路径不能为空");
            return;
        } else if (path.endsWith(SUFFIX)) {
            LogUtils.e(TAG, "文件无需加密");
            return;
        }

        RSAHelper iEncryptor = new RSAHelper.Builder()
                .setBase64Flag(flags)
                .setCharset(charset)
                .setTransformation("RSA/None/PKCS1Padding")
                .setPublicKey(PUBLIC_KEY)
                .setPrivateKey(PRIVATE_KEY)
                .build();
        new Thread(() -> {
            File source = new File(path);
            File dest = new File(Environment.getExternalStorageDirectory(), "1/rsa_encrypt/" + source.getName() + SUFFIX);
            LogUtils.d(TAG, "dest=" + dest.getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(source);
                fos = new FileOutputStream(dest);
                iEncryptor.encrypt(fis,fos);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }).start();
    }

    private void decryptFileRsa1(final String path) {
        LogUtils.d(TAG, "path=" + path);
        if (path == null) {
            LogUtils.e(TAG, "文件路径不能为空");
            return;
        } else if (!path.endsWith(SUFFIX)) {
            LogUtils.e(TAG, "文件无需解密");
            return;
        }
        RSAHelper iEncryptor = new RSAHelper.Builder()
                .setBase64Flag(flags)
                .setCharset(charset)
                .setTransformation("RSA/None/PKCS1Padding")
                .setPublicKey(PUBLIC_KEY)
                .setPrivateKey(PRIVATE_KEY)
                .build();
        new Thread(() -> {
            File source = new File(path);
            int index = path.lastIndexOf("/");
            File dest = new File(Environment.getExternalStorageDirectory(), "1/rsa_decrypt/" + path.substring(index + 1).replace(SUFFIX, ""));
            LogUtils.d(TAG, "dest=" + dest.getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(source);
                fos = new FileOutputStream(dest);
               iEncryptor.decrypt(fis,fos);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == REQUEST_ENCRYPT_FILE) {
                //加密
                String pathFromUri = UriUtils.getPathFromUri(this, data.getData());
                encryptFileAes(pathFromUri);
            } else if (requestCode == REQUEST_DECRYPT_FILE) {
                //解密
                String pathFromUri = UriUtils.getPathFromUri(this, data.getData());
                decryptFileAes(pathFromUri);
            }
        }

    }


}
